<?php
namespace Home\Controller;

use Think\Controller;

class PayController extends CommonController
{

  protected $this_table = "orders";

  public function __construct()
  {
    parent::__construct();
  }

  public function _before_xcx()
  {
    $this->check_login();
  }

  public function _before_shop_pay()
  {
    $this->check_login();
    $this->shop_close();
  }

  //商户直接付款
  public function shop_pay()
  {
    $now_time = gmtime();
    //必须是商户角色
    if ($this->types != 1) {
      return_data("error", "shop_pay.".$this->this_table.".deny", $this->types);
    }

    $tran_no = I("post.tran_no", '');

    $where['tran_no'] = $tran_no;
    $where['shop_id'] = $this->shop_id;
    $field = "*";
    $order_info = M("orders")->field($field)->where($where)->find();
    $id = $order_info['id'];
    if (!$order_info) {
      return_data("error", "order.tran_no.error");
    }

    //判断是否已支付
    if ($order_info['status']>0) {
      return_data("error", "order.status.error");
    }

    //改变支付状态
    $where = array();
    $where['id'] = $id;
    $update_data['status'] = 2;
    $update_data['pay_mode'] = 3;
    $update_data['payed_at'] = $now_time;
    $result = M("orders")->where($where)->save($update_data);

    $detail = M('order_children')->where("order_id=$order[id]")->find();
    $product = M('products')->where("id=$detail[product_id]")->find();

    $data['product_num'] = $product['product_num']-$detail['product_num'];

    if($data['product_num']<0){
      $data['product_num'] = 0;
    }
    $products = M('products')->where("id=$detail[product_id]")->save($data);

    if (!$result) {
      return_data("error", "shop_pay.orders.error");//blank
    } else {
      return_data("success", "shop_pay.orders.success");
    }
  }

  /**
   * [小程序支付请求]
   * @return [type] [description]
   */
  public function xcx()
  {
    Vendor("Wxpay.WxPayApi");

    $data = file_get_contents('php://input');
    $data = json_decode($data, true);

    if (!$data['tran_no']) {
      return_data("error", "xcx_pay.tran_no.empty");
    } else {
      $where['tran_no'] = $data['tran_no'];
      $order_info = M("orders")->field('*')->where($where)->find();
      if (!$order_info) {
        return_data("error", "order.tran_no.error");
      }
      if($order_info['shop_id']){
        $this->shop_id = $order_info['shop_id'];
        $this->shops_close();
      }
      //判断是否已支付
      if ($order_info['status'] > 1) {
        return_data("error", "order.status.error");
      }

      //获取支付金额
      $total_amount = $order_info['total_amount'];
      if ($total_amount < 0.01) {
        return_data("error", "order.total_amount.too.little");
      }
    }

    $user = M("users")->field('*')->where(array('id' => $order_info['user_id']))->find();
    if (!$user) {
      return_data("error", "user.not.exist");
    }

    $order_child = M('order_children')->where(array('order_id' => $order_info['id']))->find();

    $id = $order_child['product_id'];
    $goods = M('products')->where("id=$id")->find();
    if($goods['status']==0){
      return_data('error','status');
    }
    $specs = M('specs')->where(array('id' => $order_child['spec_id']))->find();
    if($specs){
      if($order_child['product_num'] > $specs['stock']){
        return_data('error','product.num.error');
      }
    }else{
      if($goods['is_platform']==1 && $goods['pf_id']>0){
          $goods_check = M("products")->where("id=$goods[pf_id]")->find();
          if($order_child['product_num'] > $goods_check['product_num']){
            return_data("error", "product.num.error");
          }
          if($goods_check['status']!=1){
            return_data('error','status');
          }
      }else{
        if($order_child['product_num'] > $goods['product_num']){
          return_data('error','product.num.error');
        }         
      }
    }

    $body = "{$order_child['product_name']} 等商品";

    $total_fee = $total_amount * 100;
    // $total_fee = 1 * 100;


    $input = new \WxPayUnifiedOrder();
    $input->SetBody($body);
    // $input->SetAttach("小程序支付");
    $input->SetOut_trade_no($data['tran_no']);
    $input->SetTotal_fee($total_fee);
    $input->SetSpbill_create_ip(get_client_ip());
    // $input->SetTime_start(date("YmdHis"));
    // $input->SetTime_expire(date("YmdHis", time() + 600));
    // $input->SetGoods_tag("test");
    // $notify_url = 'https://'.$_SERVER['HTTP_HOST']."/v1/pay/notify";

    $app_info = $this->app_info;
    $protocol = is_ssl() ? 'https' : 'http';
    $notify_url = "{$protocol}://{$_SERVER['HTTP_HOST']}/addons/zjhj_wdds/core/notify";
    $input->SetNotify_url($notify_url);

    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($user['xcx_openid']);
    $input->SetAppid($app_info['cappid_applet']);
    $input->SetMch_id($app_info['mch_id']);
    $input->SetKey($app_info['xcx_key']);

    $result = \WxPayApi::unifiedOrder($input);

    $result['pay_sign'] = md5("appId={$result['appid']}&nonceStr={$result['nonce_str']}&package=prepay_id={$result['prepay_id']}&signType=MD5&timeStamp={$this->current_time}&key={$app_info['xcx_key']}");
    $result['timestamp'] = $this->current_time;

    if ($result['return_code'] == "SUCCESS") {
      return_data("success", "xcx.payment.success", $result);
    } else {
      return_data("error", "xcx.payment.error", $result);
    }
  }

  /**
   * [微信小程序支付notify]
   * @return [type] [description]
   */
  public function notify()
  {
    $result = I('');

    if ($result['result_code'] == 'SUCCESS' && $result['sign']) {
      $fields = "o.*,s.alipay_name as alipay_name,s.alipay_account as alipay_account,s.rate as rate, s.app_id as app_id";
      $order = M("Orders")->alias("o")
                ->join("left join ".C("DB_PREFIX")."shops s on s.id=o.shop_id")
                ->field($fields)
                ->where(array('o.tran_no' => $result['out_trade_no']))
                ->find();

      $return_data['return_code'] = 'FAIL';
      if ($order && $order['status'] == 1) {
        $data['status'] = 2;
        $data['pay_mode'] = 1;
        $data['transaction_id'] = (string)$result['transaction_id'];
        $data['xcx_openid'] = (string)$result['openid'];
        $data['payed_at'] = $order['payed_at'] = $this->current_time;

        $result = M('orders')->where("id=$order[id]")->save($data);
        $detail = M('order_children')->where("order_id=$order[id]")->find();
        $product = M('products')->where("id=$detail[product_id]")->find();

        $specs = M('specs')->where(array('id' => $detail['spec_id']))->find();
        if($specs){
           $list['stock'] = $specs['stock']-$detail['product_num'];
            if($list['stock']<0){
                $list['stock'] = 0;
            }
            $products = M('specs')->where(array('id'=>$detail['spec_id']))->save($list);
        }else{

          if($product['is_platform']==1 && $product['pf_id'] >0){
            $goods_check = M("products")->where("id=$product[pf_id]")->find();

            if($goods_check){
              $list['product_num'] = $goods_check['product_num'] - $detail['product_num'];
              if($list['product_num'] < 0){
                 $list['product_num'] = 0;
              }
              $products = M('products')->where("id=$product[pf_id]")->save($list);
            }

          }else{

            $list['product_num'] = $product['product_num']-$detail['product_num'];
            if($list['product_num']<0){
                $list['product_num'] = 0;
            }
            $products = M('products')->where("id=$detail[product_id]")->save($list);    
          }
        }

        $pay_log = array(
          'order_tran_no' => $order['tran_no'] ,
          'order_id' => $order['id'],
          'created_at' => $this->current_time);
        M('pay_logs')->create($pay_log);
        M('pay_logs')->add();

        // $order['status'] = 2;
        // add_alipay_queue($order);
        // $app = M('apps')->field('alipay_max_amount')->where("id={$order['app_id']}")->find();
        // if ($order['total_amount'] <= $app['alipay_max_amount']) {
        //   //alipay_to_shop($order);
        // }
        if ($order['is_platform'] == 1) {
          #生成提醒消息
          $msg = array(
            'app_id' => $order['app_id'],
            'user_id' => $order['user_id'],
            'order_id' => $order['id'],
            'content' => "新的订单已支付，订单号{$order['tran_no']}",
            'status' => 0,
            'types' => 4
          );
          $msg['created_at'] = $msg['updated_at'] = $this->current_time;
          M('messages')->add($msg);
        } else {
          $unbilled_amount = M("Shops")->where("id = {$order['shop_id']}")->getField('unbilled_amount');
          $unbilled_amount += $order['total_amount'];
          M("Shops")->where("id = {$order['shop_id']}")->save(array("unbilled_amount" => $unbilled_amount));
          send_payed_message_to_shop($order);
        }


        //打印订单
        // $shop = M('shops')->where("id=$order[shop_id]")->find();

        // if ($shop['print_num'] > 0) {
        //   $order = M('orders')->where("id=$order[id]")->find();
        //   $products = M('order_children')->where("order_id={$order[id]}")->select();
        //   $order['children'] = $products;
        //   //print_order($order, $shop);
        // }

        $return_data['return_code'] = 'SUCCESS';
      };
      if ($order && $order['status'] == 3) {
        \Think\Log::record(json_encode($order),'WARN');
      }
    } else {
      $return_data['return_code'] = 'FAIL';
      $return_data['return_msg'] = '操作失败';
    }

    echo array_to_xml($return_data);
  }
}
